<?php

namespace App\Models;

use function GuzzleHttp\Promise\is_fulfilled;
use Illuminate\Database\Eloquent\Model;

/**
 * 系统消息
 */
class Message extends Model
{
    protected $table = 'message';

    protected $fillable = [
        'admin_id',
        'uid',
        'title',
        'content',
        'type',
        'is_read',
        'tpl_id',
    ];

    public function admin()
    {
        return $this->hasOne('App\Models\Admin','id','admin_id');
    }

    /**
     * 获取模板信息
     * @author: yanggang
     * @date: 2018/5/18 0018
     * @param array $msg 形如['msg_id'=>1,'uid'=>1,'message'=>['系统消息'],'push_message'=>['推送消息'],'title'=>[]]
     * @return mixed
     * @throws \Exception
     */
    protected function getTplMsg(array $msg)
    {
        //格式化消息
        if (!key_exists('msg_id',$msg)){
            throw new \Exception('消息模板msg_id必须');
        }
        $list = (new MessageTpl())
            ->select('name','title','message','icon','push_message','push','system')
            ->find($msg['msg_id']);
        if (empty($list)){
            throw new \Exception('消息模板不存在');
        }
        $list = $list->toArray();
        $msg_name = ['未知','系统消息'];
        $list['name'] = $msg_name[$list['name']];

        $system = $list['system']==0 ? '':$this->msgFormat($list,$msg); //系统消息
        $push = $list['push']==0?'':$this->msgFormat($list,$msg,1); //推送消息
        $title = $this->msgFormat($list,$msg,2); //标题
        $icon = empty($list['icon'])?'':config('alioss.host').'/'.$list['icon']; //图片

        $list['icon'] = $icon;
        $list['message'] = $system;
        $list['push_message'] = $push;
        $list['title'] = $title;


        return $list;
    }

    /**
     * 格式化模板信息
     * @author: yanggang
     * @date: 2018/5/18 0018
     * @param $list
     * @param $msg
     * @param int $type 0 系统消息 1 推送消息 2 标题
     * @return string
     * @throws \Exception
     */
    protected function msgFormat($list,$msg,$type=0)
    {
        $type_name = ['message', 'push_message','title']; //type 对应的字段
        $key = $type_name[$type];

        $notice = ['系统消息模板','推送消息模板','标题'];

        //格式化模板消息

        $count = substr_count($list[$key], '%s');

        if ($count && (!key_exists($key, $msg) || count($msg[$key]) != $count)) {
            throw  new  \Exception($notice[$type].'格式化参数不匹配');
        }

        if (!$count && !key_exists($key, $msg)) {
            return $list[$key];
        }

        return vsprintf($list[$key], $msg[$key]);

    }


    /**
     * 入用户消息表和极光推送
     * @author: yanggang
     * @date: 2018/5/18 0018
     * @param array $msg 形如['msg_id'=>1,'uid'=>1,'message'=>['系统消息','系统消息1',...],'push_message'=>['推送消息','推送消息1,...],'title'=>['标题']]
     *                   如果对应键名没有格式化的内容，则不用传该参数 例如['msg_id'=>11,'uid'=>31]
     * @return mixed
     * @throws \Exception
     */
    public function syspublishsmsAll(array $msg)
        {
        //字段检查
        if (empty($msg) || !is_array($msg)) {
            return false;
        }
        if (!isset($msg[0])){ //如果传递的1维数组 改为2维数组

            $msg = [$msg];
        }
        $user_model = new User();
        foreach ($msg as $item){
            $list = $this->getTplMsg($item);

            //入用户消息表
            if ($list['system'] == 1){
                $sys_data = [
                    'admin_id'=>session('admin_info.id')??0,
                    'uid' =>  $item['uid'] ??0,
                    'title'=>$list['title'],
                    'content'=>$list['message'],
                    'type'=>$item['uid'] ? 1 : 0,
                    'is_read'=>0,
                    'tpl_id'=>$item['msg_id'],
                ];
                $this->create($sys_data);
            }

            //极光推送
            if ($list['push'] == 1 ){
                $uid = $item['uid'];
                $title = $list['title'];
                $push_message = $list['push_message'];
                if ($uid){
                    //指定用户发,获取token
                    $token = substr($user_model->where('id','=',$uid)->value('token'),0,6);
                    $key = $uid.$token;
                    $push_arr = [];
                    if(!empty($item['arr'])){
                        $push_arr = $item['arr'];
                    }
                    (new Send())->send(1,$key,$title,$push_message,$item['msg_id'],$push_arr);
                }else{
                    (new Send())->sends($title ,$push_message,1,$item['arr']);
                }

            }
        }

    }


}
